

import React, { useState, useCallback } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, RefreshControl, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';
import CCItem from './components/CCItem';

interface CCItemData {
  id: string;
  title: string;
  applicant: string;
  status: 'processing' | 'approved' | 'rejected';
  statusText: string;
  statusColor: string;
  initiateTime: string;
  ccTime: string;
  ccReason: string;
  processId: string;
}

type FilterType = 'all' | 'processing' | 'approved' | 'rejected';
type SortType = 'time-desc' | 'time-asc' | 'title';

const CCToMeScreen = () => {
  const router = useRouter();
  
  const [searchText, setSearchText] = useState('');
  const [isFilterDropdownVisible, setIsFilterDropdownVisible] = useState(false);
  const [isSortDropdownVisible, setIsSortDropdownVisible] = useState(false);
  const [currentFilter, setCurrentFilter] = useState<FilterType>('all');
  const [currentSort, setCurrentSort] = useState<SortType>('time-desc');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);

  const [ccItems, setCcItems] = useState<CCItemData[]>([
    {
      id: '1',
      title: '员工年度调薪申请',
      applicant: '人力资源部-张三',
      status: 'processing',
      statusText: '审批中',
      statusColor: '#f59e0b',
      initiateTime: '2024-01-15 14:30',
      ccTime: '2024-01-15 15:20',
      ccReason: '相关部门负责人知悉',
      processId: 'proc-001',
    },
    {
      id: '2',
      title: '办公设备采购申请',
      applicant: '行政部-李四',
      status: 'approved',
      statusText: '已通过',
      statusColor: '#10b981',
      initiateTime: '2024-01-14 09:15',
      ccTime: '2024-01-14 10:30',
      ccReason: '财务相关审批',
      processId: 'proc-002',
    },
    {
      id: '3',
      title: '项目预算调整申请',
      applicant: '项目部-王五',
      status: 'rejected',
      statusText: '已驳回',
      statusColor: '#ef4444',
      initiateTime: '2024-01-13 16:45',
      ccTime: '2024-01-13 17:20',
      ccReason: '管理层知悉',
      processId: 'proc-003',
    },
    {
      id: '4',
      title: '员工培训费用报销',
      applicant: '技术部-赵六',
      status: 'approved',
      statusText: '已通过',
      statusColor: '#10b981',
      initiateTime: '2024-01-12 11:20',
      ccTime: '2024-01-12 13:15',
      ccReason: '部门负责人知悉',
      processId: 'proc-004',
    },
    {
      id: '5',
      title: '会议室使用申请',
      applicant: '市场部-孙七',
      status: 'processing',
      statusText: '审批中',
      statusColor: '#f59e0b',
      initiateTime: '2024-01-11 10:00',
      ccTime: '2024-01-11 10:30',
      ccReason: '相关部门协调',
      processId: 'proc-005',
    },
  ]);

  const filteredAndSortedItems = useCallback(() => {
    let filtered = ccItems;

    // 搜索过滤
    if (searchText.trim()) {
      const searchLower = searchText.toLowerCase().trim();
      filtered = filtered.filter(
        item =>
          item.title.toLowerCase().includes(searchLower) ||
          item.applicant.toLowerCase().includes(searchLower)
      );
    }

    // 状态过滤
    if (currentFilter !== 'all') {
      filtered = filtered.filter(item => item.status === currentFilter);
    }

    // 排序
    filtered.sort((a, b) => {
      if (currentSort === 'time-desc') {
        return new Date(b.ccTime).getTime() - new Date(a.ccTime).getTime();
      } else if (currentSort === 'time-asc') {
        return new Date(a.ccTime).getTime() - new Date(b.ccTime).getTime();
      } else if (currentSort === 'title') {
        return a.title.localeCompare(b.title);
      }
      return 0;
    });

    return filtered;
  }, [ccItems, searchText, currentFilter, currentSort]);

  const handleFilterPress = useCallback(() => {
    setIsFilterDropdownVisible(!isFilterDropdownVisible);
    setIsSortDropdownVisible(false);
  }, [isFilterDropdownVisible]);

  const handleSortPress = useCallback(() => {
    setIsSortDropdownVisible(!isSortDropdownVisible);
    setIsFilterDropdownVisible(false);
  }, [isSortDropdownVisible]);

  const handleFilterOptionPress = useCallback((filterType: FilterType) => {
    setCurrentFilter(filterType);
    setIsFilterDropdownVisible(false);
  }, []);

  const handleSortOptionPress = useCallback((sortType: SortType) => {
    setCurrentSort(sortType);
    setIsSortDropdownVisible(false);
  }, []);

  const handleCCItemPress = useCallback((processId: string) => {
    router.push(`/p-approval_detail?processInstanceId=${processId}`);
  }, [router]);

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    // 模拟刷新数据
    setTimeout(() => {
      setIsRefreshing(false);
    }, 1000);
  }, []);

  const handleLoadMore = useCallback(async () => {
    if (isLoadingMore) return;
    
    setIsLoadingMore(true);
    // 模拟加载更多数据
    setTimeout(() => {
      setIsLoadingMore(false);
    }, 1000);
  }, [isLoadingMore]);

  const renderHeader = useCallback(() => (
    <View>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerTop}>
          <LinearGradient
            colors={['#6366f1', '#8b5cf6']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.titleGradient}
          >
            <Text style={styles.titleText}>抄送我的</Text>
          </LinearGradient>
          <View style={styles.headerActions}>
            <TouchableOpacity
              style={styles.actionButton}
              onPress={handleFilterPress}
              activeOpacity={0.7}
            >
              <FontAwesome6
                name="filter"
                size={18}
                color={isFilterDropdownVisible ? '#6366f1' : '#9ca3af'}
              />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.actionButton}
              onPress={handleSortPress}
              activeOpacity={0.7}
            >
              <FontAwesome6
                name="sort"
                size={18}
                color={isSortDropdownVisible ? '#6366f1' : '#9ca3af'}
              />
            </TouchableOpacity>
          </View>
        </View>

        {/* 搜索框 */}
        <View style={styles.searchContainer}>
          <View style={styles.searchInputWrapper}>
            <FontAwesome6
              name="magnifying-glass"
              size={16}
              color="#9ca3af"
              style={styles.searchIcon}
            />
            <TextInput
              style={styles.searchInput}
              placeholder="搜索审批标题、发起人..."
              placeholderTextColor="#9ca3af"
              value={searchText}
              onChangeText={setSearchText}
            />
          </View>
        </View>
      </View>

      {/* 筛选下拉菜单 */}
      {isFilterDropdownVisible && (
        <View style={styles.dropdown}>
          <View style={styles.filterOptions}>
            {[
              { key: 'all', label: '全部' },
              { key: 'processing', label: '审批中' },
              { key: 'approved', label: '已通过' },
              { key: 'rejected', label: '已驳回' },
            ].map((option) => (
              <TouchableOpacity
                key={option.key}
                style={[
                  styles.filterOption,
                  currentFilter === option.key && styles.filterOptionActive,
                ]}
                onPress={() => handleFilterOptionPress(option.key as FilterType)}
                activeOpacity={0.7}
              >
                <Text
                  style={[
                    styles.filterOptionText,
                    currentFilter === option.key && styles.filterOptionTextActive,
                  ]}
                >
                  {option.label}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      )}

      {/* 排序下拉菜单 */}
      {isSortDropdownVisible && (
        <View style={styles.dropdown}>
          <View style={styles.filterOptions}>
            {[
              { key: 'time-desc', label: '时间降序' },
              { key: 'time-asc', label: '时间升序' },
              { key: 'title', label: '标题排序' },
            ].map((option) => (
              <TouchableOpacity
                key={option.key}
                style={[
                  styles.filterOption,
                  currentSort === option.key && styles.filterOptionActive,
                ]}
                onPress={() => handleSortOptionPress(option.key as SortType)}
                activeOpacity={0.7}
              >
                <Text
                  style={[
                    styles.filterOptionText,
                    currentSort === option.key && styles.filterOptionTextActive,
                  ]}
                >
                  {option.label}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      )}
    </View>
  ), [
    searchText,
    isFilterDropdownVisible,
    isSortDropdownVisible,
    currentFilter,
    currentSort,
    handleFilterPress,
    handleSortPress,
    handleFilterOptionPress,
    handleSortOptionPress,
  ]);

  const renderFooter = useCallback(() => {
    const filteredItems = filteredAndSortedItems();
    
    if (filteredItems.length === 0) {
      return (
        <View style={styles.emptyState}>
          <FontAwesome6 name="inbox" size={64} color="#4b5563" />
          <Text style={styles.emptyStateTitle}>暂无抄送记录</Text>
          <Text style={styles.emptyStateSubtitle}>您还没有收到任何抄送的审批</Text>
        </View>
      );
    }

    return (
      <View style={styles.loadMoreContainer}>
        <TouchableOpacity
          style={styles.loadMoreButton}
          onPress={handleLoadMore}
          activeOpacity={0.7}
          disabled={isLoadingMore}
        >
          {isLoadingMore ? (
            <View style={styles.loadingSpinner} />
          ) : (
            <>
              <FontAwesome6 name="chevron-down" size={14} color="#6366f1" />
              <Text style={styles.loadMoreText}>加载更多</Text>
            </>
          )}
        </TouchableOpacity>
      </View>
    );
  }, [filteredAndSortedItems, handleLoadMore, isLoadingMore]);

  const renderCCItem = useCallback(({ item }: { item: CCItemData }) => (
    <CCItem
      item={item}
      onPress={() => handleCCItemPress(item.processId)}
    />
  ), [handleCCItemPress]);

  const filteredItems = filteredAndSortedItems();

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={filteredItems}
        renderItem={renderCCItem}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={renderHeader}
        ListFooterComponent={renderFooter}
        contentContainerStyle={styles.listContent}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            tintColor="#6366f1"
            colors={['#6366f1']}
          />
        }
      />
    </SafeAreaView>
  );
};

export default CCToMeScreen;

